<%
var UpLoadClass=Class.create();
	UpLoadClass.prototype=
	{
		/* 构造函数 */
		initialize:function($options)
		{
			this.unit={kb:1024,mb:1024<<10,gb:1024<<20};
			this.setOptions($options);							//配置参数,为空使用默认参数				
			this.formData={},this.fileCdatalog={};					//表单数据及文件数据日志												
			this.stream=Server.CreateObject('ADODB.Stream');		//二进制数据存储对象
			this.temp=Server.CreateObject('ADODB.Stream');			//临时转换器
			this.stream.type=1;
			this.stream.Open();												
			this.error=0,this.description='';				
			this.count=0,this.log={};
			this.mode='debug';								//debug||standard
		},
		/* 参数设置 */
		setOptions:function($options)
		{								
			this.options={					
				charSet:'utf-8',							 //转换文本编码
				autoSave:false,								 //自动存取	
				maxSize:200*this.unit.kb,					 //文件大小200k
				totalSize:10*this.unit.mb,					 //限制数据量
				path:'../../../UpLoadFiles/',				 //文件上传路径							
				type:'gif/jpg/jpeg'							 //上传文件类型
			}.extend($options||{});
		},
		reSetOptions:function($options)					
		{
			this.options=this.options.extend($options||{});
		},
		/*　辅助方法:检查状态　*/
		state:function()
		{
			//-1:不是POST请求 0:表单entype设置不对 1:表单上传的数据大小超总限制 2:正常
			if(Request.ServerVariables('REQUEST_METHOD')=='POST')
			{
				var contentType=new String(Request.ServerVariables('CONTENT_TYPE'));
				if(contentType.indexOf('multipart/form-data')==-1) 
				{									
					return 0;
				}
				else
				{
					
					if(Request.TotalBytes>=this.options.totalSize)
					{
						return 1;
					}
					else
					{
						return 2;
					}
				}					
			}	
			else
			{
				return -1;
			}
		},
		/* 打开对象 */																					
		open:function()
		{
			switch(this.state())
			{
				case -1:
					this.throwError(7);
					break;						
				case 0:					
					this.throwError(1);
					break;
				case 1:
					this.throwError(6);
					break;
				case 2:
					var data=this.data(),limit=this.limit(data);						
					this.spider(data,limit);
					break;					
				default:
					this.throwError(9999);		
			}
		},
		/* 返回表单控件值 */	
		form:function($name)
		{
			if(this.error!=-1) return this.formData[$name];
		},
		/* 存取文件域中的文件 手动的方法 */			
		save:function($elementName)
		{
			if(this.options.autoSave) return false;									//自动存取为真禁止调用此方法
			if(this.fileCdatalog[$elementName])			
			{
				if(this.fileCdatalog[$elementName].fileSize>this.options.maxSize){	//验证文件大小  
					this.throwError(3);
					this.log[$elementName]={isUpload:false,error:this.error,description:this.description};
					return false;				
				} 
				if(!this.isFileExt(this.fileCdatalog[$elementName].fileExt)){		//验证文件扩展名
					this.throwError(4);
					this.log[$elementName]={isUpload:false,error:this.error,description:this.description};
					return false;				
				}
				this.folderObserver();
				var fileName=this.makeFileName(this.fileCdatalog[$elementName].fileExt);					
				var file=this.options.path+fileName,file=Server.MapPath(file);
					this.formData[$elementName].file=fileName;
				//开始干活
				this.temp.type=1,this.temp.open();									
				this.stream.position=this.fileCdatalog[$elementName].fileBinaryStartPosition;
				this.stream.copyTo(this.temp,this.fileCdatalog[$elementName].fileSize);
				this.temp.saveToFile(file,2);
				this.temp.close();		
				//写上传日志
				this.log[$elementName]={isUpload:true,error:0,description:''};
				return true;				
			}
			else
			{
				//没有检测到此文本域，不做任何操作
				//写日志，读取组件错误状态
				this.log[$elementName]={isUpload:false,error:this.error,description:this.description};
				return false;				
			}
		},
		/* 当autoSave设置为true时自动存取表单中的文件 */	
		saveToFile:function($elementName,$position,$length,$ext,$size)
		{
			if(!($position==undefined||!$position.constructor==Number)||($length==undefined||!$length.constructor==Number))
			{
				if($size>this.options.maxSize){											//验证文件大小  
					this.throwError(3);
					this.log[$elementName]={isUpload:false,error:this.error,description:this.description};
					return false;
				} 
				if(!this.isFileExt($ext)){												//验证文件扩展名
					this.throwError(4);
					this.log[$elementName]={isUpload:false,error:this.error,description:this.description};
					return false;
				}
				this.folderObserver();			
				var fileName=this.makeFileName(this.fileCdatalog[$elementName].fileExt);			
				var file=this.options.path+fileName,file=Server.MapPath(file);
					this.formData[$elementName].file=fileName;
				this.temp.type=1,this.temp.open();									
				this.stream.position=$position;
				this.stream.copyTo(this.temp,$length);
				this.temp.saveToFile(file,2);
				this.temp.close();
				this.log[$elementName]={isUpload:true,error:0,description:''};
				return true;				
			}
			else
			{
				//抛出错误
				this.throwError(5);
				//写日志，读取组件错误状态
				this.log[$elementName]={isUpload:false,error:this.error,description:this.description};				
				return false;
			}
		},	
		/* 爬行二进制数据流,生成表单数据，并记录文件日志 */				
		spider:function($data,$limit)
		{
			var start,finish,position3;
			var formElementName,filePath,fileName,fileExt,fileSize;
			start=$data.indexOf($limit);				
			while(start!=-1)						
			{
				//查找位置
				start+=$limit.length+2,finish=$data.indexOf($limit,start);				
				if(finish==-1) break;
				
				position3=$data.indexOf("\r\n\r\n",start);								//寻找报头的结束位置
				if(position3==-1||position3>finish) break;
				position3+=4;
				
				var head=this.toText(start,position3-start);							//获取报头字符串									
					if((formElementName=head.match(/\sname=\"(.+?)\"/))==null) break;	//寻找name属性位置
					formElementName=formElementName[1];					
					if(head.indexOf('filename')!=-1) 
					{						
							this.log[formElementName]={isUpload:false,error:0,description:''};							
					}
				var fileName=head.match(/\sfilename=\"(.+?)\"/);						//寻找filename属性位置
				if(fileName)															//找到filename属性
				{						
					fileName=fileName[1];									
					fileExt=fileName.match(/\.(\w+)$/),fileExt=fileExt[1].toLowerCase();						
					fileSize=finish-position3-4;
					//文件的相关操作
					var fileInfo=this.getFileInfo(position3,fileSize),imageWidth,imageHeight;							
					if(this.isImage(fileExt)==true)
					{
						if(fileInfo.isImage==true) 
						{	
							imageWidth=fileInfo.width;
							imageHeight=fileInfo.height;
							fileExt=fileInfo.ext;
						}
						else
						{
							this.throwError(4);
							return false;
						}
					}
					//记录文件日志与表单日志
					this.makeCdatalog({
										formElementName:formElementName,
										fileName:fileName,
										fileExt:fileExt,
										fileSize:fileSize,
										fileBinaryStartPosition:position3,
										width:((imageWidth) ? imageWidth:null),
										height:((imageHeight) ? imageHeight:null)
										});
					this.makeFormData('file',{
										name:formElementName,
										file:fileName,
										ext:fileExt,
										size:fileSize,
										width:((imageWidth) ? imageWidth:null),	
										height:((imageHeight) ? imageHeight:null)											
										});							
					//存储文件信息
					if(this.options.autoSave==true) this.saveToFile(formElementName,position3,finish-position3-4,fileExt,fileSize);										
				}
				else
				{							
					this.makeFormData('form',{
										name:formElementName,
										position:position3,
										length:finish-position3-4
										});					
				}
				start=finish;															
			}
		},			
		/* 生成表单数据 */
		makeFormData:function($type,$data)											//制作表单数据模型
		{
			//$position,$length,$name
			if($type=='form')
			{
				var formElementValue=this.toText($data.position,$data.length);												
					this.formData[$data.name]=formElementValue;
			}
			else
			{
				var fileInfo={file:$data.file,ext:$data.ext,size:$data.size,width:$data.width,height:$data.height}
					this.formData[$data.name]=fileInfo;
			}					
		},	
		/* 生成文件日志 */
		makeCdatalog:function($fileInfo)											//制作文件数据模型
		{																
			this.fileCdatalog[$fileInfo.formElementName]=$fileInfo;					
		},
		/* 表单数据 */															
		data:function()
		{
			var kb=1024,chunk=kb*200,formData;
			var size=Request.TotalBytes;
			while(size>chunk)
			{
				this.stream.write(Request.BinaryRead(chunk));
				size-=chunk;
			}
			if(size>0) this.stream.write(Request.BinaryRead(size));
			this.stream.position=0,this.stream.type=2;
			this.stream.charset="ascii";
			if(!this.stream.EOS) var formData=this.stream.readText(-1); 
			this.stream.position=0,this.stream.type=1;
			return formData;
		},	
		/* 分隔符 */				
		limit:function($data)
		{
			var start=$data.indexOf("--");
			start+=2;				
			var end=$data.indexOf("\r\n",start);
			return $data.substring(start,end);
		},
		/* 生成文件名 */			
		makeFileName:function($ext)
		{
			var myDateObj=new Date();
			var myYear,myMonth,myDate,myDay,myHours,myMinutes,mySeconds;
				myYear=(myDateObj.getYear()).toString();
				myMonth=(myDateObj.getMonth()+1).toString();
				myDate=(myDateObj.getDate()).toString();
				myHours=(myDateObj.getHours()).toString();
				myMinutes=(myDateObj.getMinutes()).toString();
				mySeconds=(myDateObj.getSeconds()).toString();
				this.count+=1;	
				return myYear+myMonth+myDate+myHours+myMinutes+mySeconds+this.count.toString()+'.'+$ext;						
		},
		/* 将二进制转换文本 */	
		toText:function($position,$length)
		{
			this.temp.type=1;
			this.temp.open();			
			this.stream.position=$position;
			this.stream.copyTo(this.temp,$length);				
			this.temp.position=0;
			this.temp.type=2;
			this.temp.charset=this.options.charSet;
			var text=this.temp.readText(-1);
			this.temp.close();
			text=text.replace(/\u0000/g,'');
			return text;
		},
		/* 文件夹监查者 */				
		folderObserver:function()
		{
			var folder=String(Server.MapPath(this.options.path)).split("\\");
			var fso_temp=Server.CreateObject('Scripting.FileSystemObject')
				var temp='';
				for(var ifolder=0;ifolder<=folder.length-1;ifolder++)
				{
					temp+=folder[ifolder]+'\\';
					if(ifolder>0)
					{			
						var tempFolder=temp.substr(0,temp.length-1);
						if(!fso_temp.FolderExists(temp.substr(0,temp.length-1))) fso_temp.CreateFolder(tempFolder);
						//echo(temp.substr(0,temp.length-1))
					}
				}
				fso_temp=null;
		},
		/* 扩展名验证 */
		isFileExt:function($ext)
		{				
			var isArray=(this.options.type.indexOf('/')!=-1),ext;
			(isArray) ? ext=this.options.type.split('/'):ext=this.options.type;		
			if(isArray)
			{
				for(var e=0;e<=this.options.type.split('/').length-1;e++)
				{	
					if(this.options.type.split('/')[e]==$ext)
						return true;
				}
				return false;
			}	
			else
			{
				return (this.options.type==$ext) ? true:false;	
			}	
		},
		/* 图象扩展名验证 */
		isImage:function($ext)
		{				
			var imageExt=['jpg','jpeg','gif','png','bmp'];
			for(var e=0;e<=imageExt.length-1;e++)
			{	
				if(imageExt[e]==$ext) return true;						
			}
			return false;
		},	
		/* 取得案例文件的信息 */			
		getFileInfo:function($position,$length)
		{
			var ret = [null, 0, 0], tmp, arr,isImage=false;
			this.temp.type=1;
			this.temp.open();			
			this.stream.position=$position;
			this.stream.copyTo(this.temp,$length);				
			this.temp.position=0,this.temp.type=2;								
			this.temp.charset="UTF-16BE";
			var tmp=this.temp.readText(12);	
			var arr=tmp.toBytes();
			if (arr[0] == 0x47 && arr[1] == 0x49 && arr[2] == 0x46)
			{
				ret[0] = "gif",isImage=true;
				ret[1] = arr[7] << 8|arr[6];
				ret[2] = arr[9] << 8|arr[8];					
			}
			else if (arr[6] == 0x4A && arr[7] == 0x46 && arr[8] == 0x49 && arr[9] == 0x46)
			{
				ret[0] = "jpg",isImage=true;
				this.temp.position = 3;
				arr = this.temp.readText(-1).toBytes();
				var i = 0, k = 0, j = 0;
				while (true)
				{
					while ((i = arr[j++]) == 255);
					if (j > arr.length) break;
					if (i > 191 && i < 196) break;
					k = (arr[j++]) << 8|arr[j++];
					if ((j += k - 2) > arr.length) break;
					while ((i = arr[j++]) < 255);
					if (j > arr.length) break;
				}
				j += 3;
				if (j + 4 < arr.length)
				{
					ret[2] = (arr[j++] << 8)|arr[j++];
					ret[1] = (arr[j++] << 8)|arr[j++];
				}
			}				
			else if (arr[1] == 0x50 && arr[2] == 0x4E && arr[3] == 0x47)
			{
				ret[0] = "png",isImage=true;
				ret[1] = arr[18] << 8|arr[19];
				ret[2] = arr[22] << 8|arr[23];
			}
			else if(arr[0] == 0x42 && arr[1] == 0x4D)
			{
				ret[0] = "bmp",isImage=true;
				ret[1] = arr[19] << 8|arr[18];
				ret[2] = arr[23] << 8|arr[22];
			}	
			this.temp.close();			
			return {isImage:isImage,ext:ret[0],width:ret[1],height:ret[2]};
		},	
		/* 删除文件 */
		deleteFile:function($path)
		{
			return FSO.deleteFile($path);
		},					
		/* 错误处理 */
		throwError:function($err)
		{
			switch($err)
			{
				case 1:
					var errorDescription='表单设置出错,请将表单的enctype属性值设置为multipart/form-data,以便组件能够正常工作';
					this.error=1,this.description=errorDescription;
					if(this.mode=='debug') doc(errorDescription),over();																		
					break;
				case 2:
					var errorDescription='表单无此控件';						
					this.error=2,this.description=errorDescription;						
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();									
					}
					break;	
				case 3:	
					var errorDescription='文件超过大小限制,单个文件的大小不能超过 '+this.options.maxSize+' 字节。';									
					this.error=3,this.description=errorDescription;						
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();					
					}
					break;
				case 4:
					var errorDescription='文件扩展名不对，只能是 '+this.options.type.replace(/\//g,' ')+' 其中的一种。';						
					this.error=4,this.description=errorDescription;
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();
					}											
					break;
				case 5:
					var errorDescription='自动上传文件失败';						
					this.error=5,this.description=errorDescription;
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();
					}	
					break;
				case 6:
					var errorDescription='一次性上传到服务器的文件总大小,不能超过'+this.options.totalSize+'字节.';						
					this.error=6,this.description=errorDescription;
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();
					}	
					break;
				case 7:
					var errorDescription='表单的请求方法,不是POST方法.';						
					this.error=7,this.description=errorDescription;
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();
					}	
					break;																		
				default:
					var errorDescription='发生意外未错误';						
					this.error=-1,this.description=errorDescription;
					if(this.mode=='debug') 
					{
						doc(errorDescription),over();
					}
			}
		},	
		/* 释放以象 */																		
		close:function()
		{
			this.options=null;
			this.formData=null,this.fileCdatalog=null,this.log=null;	
			this.error=null,this.errorDescription=null,this.mode=null;							
			this.stream.Close();
			delete this.stream;
			delete this.temp;		
		}			
	};
%>
